﻿using System;
using System.Text;

namespace FWF.Logging.Viewer
{
    /// <summary>
    /// Contains helper functions for handling and reporting exceptions.
    /// </summary>
    public static class ExceptionLib
    {

        /// <summary>
        /// Returns a formatting string that contains the full report of an <see cref="Exception"/> and all inner exceptions.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <returns></returns>
        public static string FormatException( Exception ex )
        {
            if ( ex == null )
            {
                return string.Empty;
            }

            // Format Stack Trace from all wrapped exceptions
            var messageBuilder = new StringBuilder();
            var stackTraceBuilder = new StringBuilder();

            messageBuilder.Append( ex.Message );
            stackTraceBuilder.Append( ex.StackTrace );

            while ( ex.InnerException != null )
            {
                ex = ex.InnerException;

                // Append exception message
                messageBuilder.Append( Environment.NewLine + "-->" + ex.Message );

                // Append Stack Trace
                stackTraceBuilder.Append( Environment.NewLine + "------- INNER STACK TRACE -------" + Environment.NewLine );
                stackTraceBuilder.Append( ex.StackTrace );
            }

            if ( stackTraceBuilder.Length > 0 )
            {
                return messageBuilder + Environment.NewLine + stackTraceBuilder;
            }
            
            return messageBuilder.ToString();
        }
    }
}
